package cn.shengongying.api.config;

import cn.shengongying.bean.ResponseResult;
import cn.shengongying.enums.ResponseCodeEnum;
import cn.shengongying.exception.ParamException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * author: RXK
 * date: 2022/1/5 星期三
 * desc:
 */
@RestControllerAdvice
public class GlobalException {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalException.class);



    @ExceptionHandler(ParamException.class)
    public ResponseResult<String> handleParamException(ParamException e) {
        return ResponseResult.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseResult<String> handleIllegalArgumentException(IllegalArgumentException e) {
        return ResponseResult.fail(ResponseCodeEnum.param_exception);
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult()
                .getFieldErrors()
                .get(0)
                .getDefaultMessage();
        return ResponseResult.fail(ResponseCodeEnum.param_exception.setMsg(message));
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseResult<String> handleException(Exception e) {
        LOGGER.error("异常:",e);
        return ResponseResult.fail();
    }
}
